﻿ 
using Admin.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using Admin.Filters;
using System.Data;
using Data.Video;
using Common.Utily;

namespace Admin.Controllers
{
    [Authorize(Roles = "Admin,SubAdmin,GM,Content")]
    [InitializeSimpleMembership]
    public class MediaController : Controller
    {  

       Htmls html = new  Htmls();
       private VideoEntities db = new VideoEntities();
        public ActionResult Edit(int id = 0)
        {
            Images images = db.Images.Find(id);
            if (images == null)
            {
                return HttpNotFound();
            }
            return View(images);
        }

        //
        // POST: /Imagess/Edit/5

        [HttpPost]
        public ActionResult Edit(Images images)
        {
            if (ModelState.IsValid)
            {
                db.Entry(images).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(images);
        }
      
        public ActionResult Index(int? CateId)
        {
            //int UserId = WebSecurity.GetUserId(User.Identity.Name);

            ViewBag.CateId = html.SelectListCate(CateId, true);
            List<Images> images = new List<Images>();
            var lst = db.Images.ToList();

            //lst = lst.Where(e => e.UserId == UserId).ToList();

            if (CateId != null)
            {
                lst = lst.Where(e => e.CateId == CateId).OrderByDescending(e => e.OrderBy).ThenBy(e=>e.Id).Take(20).ToList();
            }
            else
            {
                lst = lst.OrderByDescending(e => e.Id).OrderByDescending(e => e.OrderBy).ThenBy(e => e.Id).Take(20).ToList();
            }

            if (lst != null)
            {
                images = lst;

            }
            return View(images);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            int UserId = WebSecurity.GetUserId(User.Identity.Name);
             //e.UserId == UserId && 
            Images image = db.Images.Where(e =>e.Id == id).FirstOrDefault();
            db.Images.Remove(image);
            db.SaveChanges();
            return Redirect("/Media/Index?CateId=" + id);
        }
        //
        // POST: /Home/PreviewImage

        [HttpPost]
        public ActionResult PreviewImage()
        {
            var bytes = new byte[0];
            ViewBag.Mime = "image/png";

            if (Request.Files.Count == 1)
            {
                bytes = new byte[Request.Files[0].ContentLength];
                Request.Files[0].InputStream.Read(bytes, 0, bytes.Length);
                ViewBag.Mime = Request.Files[0].ContentType;
            }

            ViewBag.Message = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
            return PartialView();
        }

        //
        // GET: /Home/UploadImageModal

        public ActionResult UploadImageModal(int? id)
        {
            return View();
        }

        //
        // GET: /Home/UploadImage

        public ActionResult UploadImage(int? id)
        {
            ViewBag.CateId = html.SelectListCate(null, true);
            if (Request.IsAjaxRequest())
            {
                //return PartialView();
                ViewBag.Layout = "~/Views/Shared/_LayoutImagepopup.cshtml";
            }else{
                ViewBag.Layout = "~/Views/Shared/_LayoutImage.cshtml";
            }

            
            return View();
        }

        //
        // POST: /Home/UploadImage

        [HttpPost]
        public ActionResult UploadImage(UploadImageModel model)
        {
            //Check if all simple data annotations are valid
            if (ModelState.IsValid)
            {
                //Prepare the needed variables
                Bitmap original = null;
                var name = "newimagefile";
                var errorField = string.Empty;

                if (model.IsUrl)
                {
                    errorField = "Url";
                    name = GetUrlFileName(model.Url);
                    original = GetImageFromUrl(model.Url);
                }
                else if (model.IsFlickr)
                {
                    errorField = "Flickr";
                    name = GetUrlFileName(model.Flickr);
                    original = GetImageFromUrl(model.Flickr);
                }
                else if (model.File != null) // model.IsFile
                {
                    errorField = "File";
                    name = Path.GetFileNameWithoutExtension(model.File.FileName);
                    original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
                }

                //If we had success so far
                if (original != null)
                {


                      var obj = db.Category.Find(model.CateId);
                        if (obj != null)
                        {
                            model.CateName = obj.Name;
                        }
                        else
                        {
                            model.CateName = "Orther";
                        }
                      
                    int UserId = 0;
                    if (!string.IsNullOrEmpty(User.Identity.Name))
                    {
                        UserId = WebSecurity.GetUserId(User.Identity.Name);
                    }

                    int TimeNow = Datetimes.GetUnixTimestamp(DateTime.Now);
                    string folder = Strings.CreateUrl(model.CateName);
                    string fileName = name + TimeNow + ".png";
                    string path = "/Content/Media/imgs/" + folder + "/";
                    string pathThumbnail = "/Content/Media/imgs/Thumbnail/" + folder + "/";

                    bool isExists = System.IO.Directory.Exists(Server.MapPath(pathThumbnail));
                    if (!isExists)
                        System.IO.Directory.CreateDirectory(Server.MapPath(pathThumbnail));

                    isExists = System.IO.Directory.Exists(Server.MapPath(path));
                    if (!isExists)
                        System.IO.Directory.CreateDirectory(Server.MapPath(path));



                    var img = CreateImage(original, model.X, model.Y, model.Width, model.Height);
                    //Demo purposes only - save image in the file system

                    var fn = Server.MapPath("~" + path + fileName);
                    img.Save(fn, System.Drawing.Imaging.ImageFormat.Png);


                    int height = 120;
                    int width = 120;
                    if (img.Width > img.Height)
                        height = img.Height * width / img.Width;
                    else
                        width = img.Width * height / img.Height;

                    Image thumb = img.GetThumbnailImage(width, height, () => false, IntPtr.Zero);
                    thumb.Save(Server.MapPath("~" + pathThumbnail + fileName), System.Drawing.Imaging.ImageFormat.Png);

                    Images image = new Images();
                    if (string.IsNullOrEmpty(model.Title))
                    {
                        image.Title = name;
                    }
                    else {
                        image.Title = model.Title;
                    }
                    
                    image.Height = img.Height;
                    image.Width = img.Width;
                    image.Url = folder +"/"+ fileName;
                    image.Thumbnail =model.Link+"";
                    image.FileType = 0;
                    image.CateId = model.CateId;
                    image.CateName = model.CateName;
                    image.UserId = UserId;
                    db.Images.Add(image);
                    db.SaveChanges();
                    return Redirect("/Media/Index?CateId=" + model.CateId);
                }
                else //Otherwise we add an error and return to the (previous) view with the model data
                    ModelState.AddModelError(errorField, "Tải lên của bạn dường như không hợp lệ. Vui lòng thử lại bằng cách sử dụng hình ảnh chỉ đúng!");
            }

            return View(model);
        }




        /// <summary>
        /// Gets an image from the specified URL.
        /// </summary>
        /// <param name="url">The URL containing an image.</param>
        /// <returns>The image as a bitmap.</returns>
        Bitmap GetImageFromUrl(string url)
        {
            var buffer = 1024;
            Bitmap image = null;

            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
                return image;

            using (var ms = new MemoryStream())
            {
                var req = WebRequest.Create(url);

                using (var resp = req.GetResponse())
                {
                    using (var stream = resp.GetResponseStream())
                    {
                        var bytes = new byte[buffer];
                        var n = 0;

                        while ((n = stream.Read(bytes, 0, buffer)) != 0)
                            ms.Write(bytes, 0, n);
                    }
                }

                image = Bitmap.FromStream(ms) as Bitmap;
            }

            return image;
        }

        /// <summary>
        /// Gets the filename that is placed under a certain URL.
        /// </summary>
        /// <param name="url">The URL which should be investigated for a file name.</param>
        /// <returns>The file name.</returns>
        string GetUrlFileName(string url)
        {
            var parts = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var last = parts[parts.Length - 1];
            return Path.GetFileNameWithoutExtension(last);
        }

        /// <summary>
        /// Creates a small image out of a larger image.
        /// </summary>
        /// <param name="original">The original image which should be cropped (will remain untouched).</param>
        /// <param name="x">The value where to start on the x axis.</param>
        /// <param name="y">The value where to start on the y axis.</param>
        /// <param name="width">The width of the final image.</param>
        /// <param name="height">The height of the final image.</param>
        /// <returns>The cropped image.</returns>
        Bitmap CreateImage(Bitmap original, int x, int y, int width, int height)
        {
            var img = new Bitmap(width, height);

            using (var g = Graphics.FromImage(img))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(original, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
            }

            return img;
        }
        private void ImageResults(string fileName, Image img, int width, int height)
        {

        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
    
    public class ImageResult : FileStreamResult
    {
        public ImageResult(Image input)
            : this(input, input.Width, input.Height)
        {
        }

        public ImageResult(Image input, int width, int height)
            : base(GetMemoryStream(input, width, height, ImageFormat.Png), "image/png")
        {
        }

        public static MemoryStream GetMemoryStream(Image input, int width,
                                                    int height, ImageFormat fmt)
        {
            // maintain aspect ratio 
            if (input.Width > input.Height)
                height = input.Height * width / input.Width;
            else
                width = input.Width * height / input.Height;

            var bmp = new Bitmap(input, width, height);
            var ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Png);
            ms.Position = 0;
            return ms;
        }
    }
}
